package net.huadong.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * 异步非阻塞IO 服务线程
 */
public class AsyncTimeServerHandler implements Runnable {
    private int port;
    CountDownLatch latch;
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port) {
        this.port = port;
        try {
            //创建异步非阻塞IO通道
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            //绑定监听端口
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("服务端启动,端口：" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //允许当前线程阻塞，待其他子线程执行完后执行，demo演示用，防止执行完程序关闭，实际应用中，不需要以线程的形式来处理AsynchronousServerSocketChannel
        latch = new CountDownLatch(1);
        doAccept();//监听接收
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doAccept() {
        //调用通道的accept监听，初始化一个handler实例  AcceptCompletionHandler
        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
    }
}
